package com.samsung.sharepoint;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

/* This class is used to receive the files from the client, It listens on a server Socket */

public class FileServerService extends Service {

	ServerSocket fileServerSocket;
	String SERVERIP;
	int FILESERVERPORT = 8890;
	String option = "";
	Messenger messenger;

	/*
	 * This function is called whenever a service is started or a startService
	 * and creates a thread that receives a file
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		option = intent.getStringExtra("option");
		SERVERIP = intent.getStringExtra("serverip");
		Bundle extras = intent.getExtras();
		messenger = (Messenger) extras.get("handler");
		/* This thread initiataes receiving the file */

		Thread fst1 = new Thread(new FileServerThread());
		fst1.start();
		return super.onStartCommand(intent, flags, startId);

	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	/*
	 * this thread initiates recieving files
	 */
	public class FileServerThread implements Runnable {

		/* this is called when the thread starts */
		public void run() {
			try {
				if (SERVERIP != null) {
					fileServerSocket = new ServerSocket(FILESERVERPORT);
					try {
						while (true) {
							Socket client = fileServerSocket.accept();
							while (true) {
								if (option.equals("case1")
										|| option.equals("case2"))
									break;
							}
							/*
							 * this takes in a file and saves it in the external
							 * storage directory
							 */
							if (option.equals("case1")) {
								Log.d("FileServerService", "option is case 1");
								// Accepts the connection
								DataOutputStream dout = new DataOutputStream(
										client.getOutputStream());
								dout.writeUTF("accepted");
								// Create an input Stream
								DataInputStream din = new DataInputStream(
										client.getInputStream());
								final String fileName = din.readUTF();
								// Save the input stream to the external storage
								File f = new File(
										Environment
												.getExternalStorageDirectory()
												+ "/" + fileName);
								FileOutputStream fout = new FileOutputStream(f);
								int fileLength = din.readInt();
								int foutLen = 0;
								int len = 0;
								byte[] buf = new byte[64 * 1024];
								while (foutLen != fileLength) {
									Log.d("FileServerService",
											"Recieving File...");
									len = din.read(buf);
									fout.write(buf, 0, len);
									foutLen += len;
								}
								Log.d("FileServerService", "File Received");
								Message msg1 = Message.obtain();
								msg1.obj = "File Received:"
										+ Environment
												.getExternalStorageDirectory()
										+ "/" + fileName;
								messenger.send(msg1);
								// Close all connections
								fout.flush();
								fout.close();
								din.close();
								dout.close();
								Log.d("FileServerService",
										"File saved"
												+ Environment
														.getExternalStorageDirectory()
												+ "/" + fileName);
							}

						}
					} catch (Exception e) {

						Log.d("FileServerService",
								"Exception in file server thread");
						e.printStackTrace();
					}

				} else {

					Log.d("FileServerService",
							"Couldn't detect internet connection.");
				}
			} catch (Exception e) {

				Log.d("FileServerService", "Error");
				e.printStackTrace();
			}
		}
	}

}
